/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.mobao.marshal;

import com.acooly.core.utils.Exceptions;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiMarshal;
import com.acooly.module.openapi.client.api.marshal.ApiMarshalSupport;
import com.acooly.module.openapi.client.api.util.XStreams;
import com.acooly.module.openapi.client.provider.mobao.domain.MoBaoRequest;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhangpu
 */
public class MoBaoRequestMarshal extends ApiMarshalSupport implements ApiMarshal<String, MoBaoRequest> {

    private static final Logger logger = LoggerFactory.getLogger(ApiMarshal.class);

    protected static KeyStoreInfo keystore = new KeyStoreInfo();

    @SuppressWarnings("unchecked")
    @Override
    public String marshal(MoBaoRequest source) {
        try {
            String message = XStreams.toXmlCompact(source);
            logger.info("请求 XML:{}", message);
            String signature = getSigner(SignTypeEnum.Cert).sign(getMessage(message), keystore);
            return getPostMessage(message, signature);
        } catch (Exception e) {
            throw new ApiClientException("组装请求报文错误:" + e.getMessage());
        }
    }

    protected String getMessage(String message) {
        try {
            Base64Encoder base64Encoder = new Base64Encoder();
            message = base64Encoder.encode(message.getBytes("utf-8"));
            return message.replaceAll("\r", "").replaceAll("\n", "");
        } catch (Exception e) {
            throw Exceptions.unchecked(e);
        }
    }

    protected String getPostMessage(String message, String signature) {
        return "message=" + getMessage(message) + "&signature=" + signature;
    }

}
